package com.malamute.core.covert;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.util.StrutsTypeConverter;

import com.malamute.core.action.BaseAction;

/**
 * @author ace 时间类型转换
 * 
 */
public class DateTypeConverter extends StrutsTypeConverter {

	private static final Logger log = Logger.getLogger(DateTypeConverter.class);
	public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";

	// 暂时只考虑这几种日期格式
	public static final DateFormat[] ACCEPT_DATE_FORMATS = {
			new SimpleDateFormat(DEFAULT_DATE_FORMAT),
			new SimpleDateFormat("yyyy年MM月dd日"),
			new SimpleDateFormat("yyyy/MM/dd"),
			new SimpleDateFormat("yyyy/MM/dd hh:mm") };

	public static final String[] DATE_TYPES = { DEFAULT_DATE_FORMAT,
			"yyyy年MM月dd日", "yyyy/MM/dd", "yyyy/MM/dd hh:mm" };// 输出格式

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.struts2.util.StrutsTypeConverter#convertFromString(java.util
	 * .Map, java.lang.String[], java.lang.Class)
	 */
	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) {
		log.info(toClass);
		log.info("DateTypeConverter:" + toClass.isAssignableFrom(Date.class));
		if (toClass.isAssignableFrom(Date.class)) {
			if (values.length > 0) {
				String dateString = values[0];
				for (DateFormat format : ACCEPT_DATE_FORMATS) {
					try {
						return format.parse(dateString);// 遍历日期支持格式，进行转换
					} catch (Exception e) {
						continue;
					}
				}
			}
		}
		return null;
	}

	@Override
	public String convertToString(Map context, Object o) {
		// for(Object tmp:context.keySet()){
		// log.info("==============="+tmp);
		// }
		// log.info(context.get("action"));
		// log.info(context.get("__component_stack"));
		Object actionObject = context.get("action");
		// log.info(actionObject instanceof BaseAction);
		String dateType = "yyyy-MM-dd";
		if (actionObject instanceof BaseAction) {
			BaseAction action = (BaseAction) actionObject;
			dateType = action.getDateType();
		}
		// Form form=(Form) context.get("__component_stack");
		log.info(context.get("attr"));
		Date date = (Date) o;
		return new SimpleDateFormat(dateType).format(date);// 输出的格式是yyyy-MM-dd
	}

}
